package com.suxii.handler;

import static com.suxii.netty_demo.activity.ChatActivity.chatListAdapter;
import static com.suxii.netty_demo.activity.ChatActivity.chat_list;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;
import com.suxii.Thread.NettyThread;
import com.suxii.netty_demo.activity.Suxii;
import com.suxii.netty_demo.fragment.FriendFragment;
import com.suxii.netty_demo.fragment.MessageFragment;
import com.suxii.pojo.ChatMsg;
import com.suxii.pojo.FriendMsg;
import com.suxii.pojo.Msg;
import com.suxii.pojo.MyMsg;
import com.suxii.utils.Global;
import com.suxii.utils.NotificationUtils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.stream.Collectors;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class MyHandler extends SimpleChannelInboundHandler<Msg> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Msg msg) throws Exception {
        if (msg.getType()==Msg.CHAT_MSG) {
            ChatMsg chatMsg= (ChatMsg) msg;

            if (MessageFragment.messageAdapter != null) {
                MessageFragment.messageAdapter.setMessageViewHolder(chatMsg.getUid(), chatMsg.getContent());
                //MessageFragment.messageAdapter.notifyDataSetChanged();
            } else {
                savaMessage(chatMsg.getUid(), chatMsg.getContent());
            }


            if (chat_list != null && chatMsg.getUid() == Global.uuid) {
                chat_list.post(() -> {
                    chatListAdapter.addData(new MyMsg(0, chatMsg.getContent()));
                    chat_list.scrollToPosition(chatListAdapter.getItemCount() - 1);
                });
            }else {
                // 发送通知
                sendNotice(chatMsg);
            }


        }else if (msg.getType()==Msg.FRIEND_MSG){
            FriendMsg friendMsg= (FriendMsg) msg;
            // 去除重复元素
            Global.newFriendList.add(String.valueOf(friendMsg.getUid()));
            Global.newFriendList=Global.newFriendList.stream().distinct().collect(Collectors.toList());
            // 更新新朋友小消息数
            if (FriendFragment.friendCircleText!=null){
                FriendFragment.friendCircleText.post(() -> {
                    FriendFragment.friendCircleText.setText(Global.newFriendList.size()+"");
                });
                Suxii.circleOpenView.receiveMsg(Global.newFriendList.size()>0);
            }
        }
        Log.e("aa", msg.toString());
    }

    /*
    消息弹窗
     */
    private void sendNotice(ChatMsg chatMsg){
        String name = Global.nameOfUid.get(String.valueOf(chatMsg.getUid()));
        NotificationUtils.
                getInstance(Global.getContext())
                .sendNotice(chatMsg.getUid(),
                        name!=null? name :String.valueOf(chatMsg.getUid()),
                        chatMsg.getContent());

    }

    /*
 保存聊天信息到本地
  */
    public void savaMessage(Integer uuid, String ss) {
        String s = new Gson().toJson(new MyMsg(0, ss));
        Log.e("aa", s);
        File file = new File(Global.getContext().getFilesDir(), uuid + "_message.sx");
        try (
                var bw = new BufferedWriter(new FileWriter(file, true))
        ) {
            bw.write(s);
            bw.newLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 连接成功绑定
        Log.e("aa", "uid:" + Global.uid);
        ctx.channel().writeAndFlush(new ChatMsg("", Global.uid, "", Global.uuid));
        //ctx.channel().writeAndFlush(new ChatMsg("",222,"",222));
        Log.e("aa", "连接成功");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Log.e("aa", "断开连接,尝试重新连接...");
        if (Global.uid != 0) {
            new NettyThread().start();
        }
    }

}
